﻿using ConfExpert.Forms.Base;
using ConfExpert.Properties;
using ConfExpert.Utility;

using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevTeam;


using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class OnlineRezerve : XForm
    {
        public OnlineRezerve()
        {
            InitializeComponent();
        }

        private void OnlineRezerve_Load(object sender, EventArgs e)
        {

            this.Text = "Online Rezervasyon";

            gvRezerve.Init("GetOnlineReservation", WhoAmI);

            gvRezerve.AddDetailGrid(gvArtikel, "TrackNo");
            gvArtikel.AddDetailGrid(gvTop, "ProductId,TrackNo");

            gvRezerve.FormatAsDate("RezerveBitisTarihi");
            gvRezerve.FormatAsNumber(1, "QtyTalep");
            gvRezerve.SetCaptions("RezerveSuresi:Rez. Gün", "RezerveBitisTarihi:Rez. Bitiş", "YanitTarihi:Yanıt Tarihi", "YanitlayanId:Yanıtlayan", "OrderRef:Order Ref.", "QtyTalep:Talep Edilen Miktar", "Notes:Notlar", "ReservedBy:Talep Eden", "Email:Yanıt Adresi");
            gvRezerve.MakeReadOnly();
            gvRezerve.MakeRowSelectable();
            gvRezerve.FocusedRowChanged += gvRezerve_FocusedRowChanged;
            gvRezerve.DoubleClick += gvRezerve_DoubleClick;
            gvRezerve.MakeReadOnly();
            gvRezerve.AddSummary("QtyTalep", "ArtikelAdedi");
            gvRezerve.RowCellStyle += gvRezerve_RowCellStyle;


            gvArtikel.AddColumn("Onaylanan Miktar", typeof(decimal), "SUM(Child({FK}).QtyMT)");
            gvArtikel.MakeColumnInvisible("TrackNo");
            gvArtikel.SetCaptions("Scan:Foto", "QtySelected:Talep Edilen Miktar");
            gvArtikel.AddSummary("QtySelected", "TopAdedi", "Onaylanan Miktar");
            gvArtikel.FormatAsNumber(1, "QtySelected", "Onaylanan Miktar");
            //gvArtikel.MakeRowSelectable();
            gvArtikel.MakeReadOnly();
            gvArtikel.BestFitColumns();

            gvTop.MakeColumnInvisible("webRezerveLinesId");
            gvTop.SetCaptions("QtyRoll:Top Miktarı", "QtySelected:Talep Edilen Miktar", "QtyMT:Onaylanan Miktar");
            gvTop.MakeReadOnly("QtyMT");
            gvTop.MakeCompulsory("QtyMT");
            gvTop.FormatAsNumber(1, "QtyRoll", "QtySelected", "QtyMT");
            gvTop.Columns["QtyMT"].DisplayFormat.FormatString = "#,##0.0";

            gvTop.AddSummary("QtyRoll", "QtySelected", "QtyMT");
            gvTop.CellValueChanged += gvTop_CellValueChanged;
            gvTop.BestFitColumns();

            gvRezerve.Columns["isProcessed"].ColumnEdit = riProcessed;
            gvRezerve.YanYanaGetir("isProcessed:Durum");
            gvRezerve.MakeColumnInvisible("Durum");
            gvRezerve.SetCaptions("isProcessed:Durum");

            gvRezerve.BestFitColumns();
            SetCaption();


            GridManager gm;
            gm = GridManager.GetManager(gvTop);
            gm.GridMenu.AddMenu("Onay", TopuSec, Resources.accept_16);
            gm.GridMenu.AddMenu("Red", TopuBirak, Resources.delete_16);

            gm = GridManager.GetManager(gvArtikel);
            gm.GridMenu.AddMenu("Onay", ArtikeliSec, Resources.accept_16);
            gm.GridMenu.AddMenu("Red", ArtikeliBirak, Resources.delete_16);


            gvRezerve.Columns["YanitlayanId"].ColumnEdit = RI(Rp.V_User);

            btnSave.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            btnSave.ItemClick += btnSave_ItemClick;
        }

        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvArtikel.EndEditing();
            gvRezerve.EndEditing();
            gvTop.EndEditing();
            DataRow dr = gvRezerve.GetFocusedDataRow();
            if (dr != null)
            {
                int TrackNo = (int)dr["TrackNo"];
                DataTable dtTop = gvTop.DataTable();
                DataTable dtRoll = dtTop.Select("TrackNo =" + TrackNo.ToString()).CopyToDataTable();

                if (dtRoll.Select("QtyMT is null").Length > 0)
                {
                    XtraMessageBox.Show("Onay veya Red verilmemiş toplar var.", "Hata");
                    return;
                }

                DataTable dtx = dtRoll.DefaultView.ToTable(false, "webRezerveLinesId", "QtyMT");
                string xml = dtx.Serialize();
                Session.DataManager.ExecuteNonQuery("UpdOnlineReservation", TrackNo, WhoAmI, xml);
                tabs.SelectedTabPageIndex = 0;
                gvRezerve.SetFocusedRowCellValue("isProcessed", 1);
            }
        }

        int TrackNo;
        DataRow[] GetTopP(int TrackNo, int ProductId)
        {
            return gvTop.DataTable().Select(string.Format("TrackNo= {0} AND ProductId = {1}", TrackNo, ProductId));
        }

        void ArtikeliSec(object sender, EventArgs e)
        {
            if (gvArtikel.SelectedRowsCount < 1)
                gvArtikel.SelectRow(gvArtikel.FocusedRowHandle);

            foreach (int handle in gvArtikel.GetSelectedRows())
            {
                TrackNo = gvArtikel.GetRowCellValue(handle, "TrackNo").ToInt(-1);
                int ProductId = gvArtikel.GetRowCellValue(handle, "ProductId").ToInt(-1);
                foreach (DataRow row in GetTopP(TrackNo, ProductId))
                    row["QtyMT"] = row["QtySelected"];
            }
        }

        void ArtikeliBirak(object sender, EventArgs e)
        {
            if (gvArtikel.SelectedRowsCount < 1)
                gvArtikel.SelectRow(gvArtikel.FocusedRowHandle);

            foreach (int handle in gvArtikel.GetSelectedRows())
            {
                TrackNo = gvArtikel.GetRowCellValue(handle, "TrackNo").ToInt(-1);
                int ProductId = gvArtikel.GetRowCellValue(handle, "ProductId").ToInt(-1);
                foreach (DataRow row in GetTopP(TrackNo, ProductId))
                    row["QtyMT"] = 0;
            }
        }

        void TopuSec(object sender, EventArgs e)
        {
            if (gvTop.SelectedRowsCount < 1)
                gvTop.SelectRow(gvTop.FocusedRowHandle);

            foreach (int handle in gvTop.GetSelectedRows())
                gvTop.GetDataRow(handle)["QtyMT"] = gvTop.GetDataRow(handle)["QtySelected"];
        }

        void TopuBirak(object sender, EventArgs e)
        {
            if (gvTop.SelectedRowsCount < 1)
                gvTop.SelectRow(gvTop.FocusedRowHandle);

            foreach (int handle in gvTop.GetSelectedRows())
                gvTop.GetDataRow(handle)["QtyMT"] = 0;
        }


        void gvTop_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow dr = gvTop.GetDataRow(e.RowHandle);
            decimal qty = 0;
            object val = e.Value;
            if (val != DBNull.Value)
                qty = val.ToDecimal();

            if (qty > (decimal)dr["QtyRoll"])
                qty = (decimal)dr["QtyRoll"];

            dr["QtyMT"] = qty;
        }

        void gvRezerve_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1 && e.Column.FieldName == "isProcessed")
            {
                int durum = 0;

                if (e.CellValue != null && e.CellValue != DBNull.Value)
                    durum = (int)e.CellValue;

                e.Appearance.Font = new System.Drawing.Font(e.Appearance.Font, FontStyle.Bold);

                if (durum == 0)
                    e.Appearance.BackColor = Color.FromName(AppSession.PrgSettingsOrg.ZorunluAlanRengi);
            }
        }
        /*
        RepositoryItemLookUpEdit riDurum
        {
            get
            {
                RepositoryItemLookUpEdit ri = new RepositoryItemLookUpEdit();

                DataTable dt = new DataTable();
                dt.Columns.Add("Display", typeof(string));
                dt.Columns.Add("Value", typeof(byte));
                dt.Rows.Add("Onaylandı", 1);
                dt.Rows.Add("Reddedildi", 2);
                ri.DisplayMember = "Display";
                ri.ValueMember = "Value";
                ri.NullText = "Açık";
                ri.DataSource = dt;
                return ri;
            }
        }
        */
        RepositoryItemLookUpEdit riProcessed
        {
            get
            {
                RepositoryItemLookUpEdit ri = new RepositoryItemLookUpEdit();

                DataTable dt = new DataTable();
                dt.Columns.Add("Display", typeof(string));
                dt.Columns.Add("Value", typeof(byte));
                dt.Rows.Add("İşlendi", 1);
                ri.DisplayMember = "Display";
                ri.ValueMember = "Value";
                ri.NullText = "Yeni";
                ri.DataSource = dt;
                return ri;
            }
        }


        void gvRezerve_DoubleClick(object sender, EventArgs e)
        {
            Point pt = gvRezerve.GridControl.PointToClient(Control.MousePosition);
            GridHitInfo info = gvRezerve.CalcHitInfo(pt);

            if (info.InRow || info.InRowCell)
            {
                btnSave.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                tabs.SelectedTabPageIndex = 1;
                object oKapandi = gvRezerve.GetFocusedDataRow()["isProcessed"];
                if (oKapandi != DBNull.Value)
                    btnSave.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }
        }

        void gvRezerve_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            SetCaption();
        }

        private void SetCaption()
        {
            DataRow dr = gvRezerve.GetFocusedDataRow();
            if (dr != null)
                txtInfo.Caption = "TrackNo " + dr["TrackNo"].ToString() + ". OrderRef " + dr["OrderRef"].ToString();
        }

        private void tabs_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            btnSave.Visibility = (tabs.SelectedTabPageIndex == 1) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
            SetMainToolbarVisibility();
        }

        private void SetMainToolbarVisibility()
        {
            if (btnSave.Visibility == DevExpress.XtraBars.BarItemVisibility.Always)
                MainToolbar.Visible = true;
            else
                MainToolbar.Visible = false;
        }

        //private void btnReddet_Click(object sender, EventArgs e)
        //{
        //     DataRow dr = gvRezerve.GetFocusedDataRow();
        //     if (dr != null)
        //     {
        //         int TrackNo = (int)dr["TrackNo"];
        //         Session.DataManager.ExecuteNonQuery("OnlineReservationRed", TrackNo, WhoAmI);
        //         gvRezerve.SetFocusedRowCellValue("Durum", 2);
        //         ShowMessage("İstek reddedildi.");
        //     }
        //}

    }
}
